#include"mycp.h"

#define CACHE 256
#define MAX_CACHE 1024

int file2file(int fin, int fout)
{
	char* bufs = (char *)malloc(MAX_CACHE);
	ssize_t ret;
	int total = 0;
	while((ret = read(fin, bufs, MAX_CACHE)) != 0)   // 文件拷贝
	{
		if (ret == -1) 
		{
        	if (errno == EINTR) 
		{
            	continue;     
        	}
        	perror("read");
        	break;
    		}
		write(fout, bufs, ret);
	}

	free(bufs);

return 1;
}

void mycp(char *sourcePath,char *targetPath)
{
    int f1 = open(sourcePath, O_RDONLY);
	if (f1 == -1)                       // 源文件不存在
	{
		perror(sourcePath);
        return;
	}

    int f2 = open(targetPath, O_WRONLY|O_CREAT, S_IRUSR | S_IWUSR);
    if (f2 == -1)
    {
        perror(targetPath);
        return;
    }
    file2file(f1, f2);
    printf("%s%s\n", "file cp to target: ", targetPath);

    // 关闭文件
    close(f1);
    close(f2);
}


